import { createRouter, createWebHistory } from "vue-router";

import LoginVue from "@/views/Login.vue";
import aabb from "@/views/aabb.vue";

import ArticleCategory from "@/views/article/ArticleCategory.vue";
import ArticleManage from "@/views/article/ArticleManage.vue";
import UserAvatar from "@/views/user/UserAvatar.vue";
import Userinfo from "@/views/user/UserInfo.vue";
import UserResetPassword from "@/views/user/UserResetPassword.vue";
import Login from "../views/Login.vue";
import Register from "../views/Register.vue";
import Home from "../views/Home.vue";


//定义路由关系
const routes = [
  {
    // 重定向，默认访问的页面,访问/就默认跳转到/article/ArticleManage
    path: "/",
    component: aabb,
    redirect: "/article/ArticleManage",
    // 子路由（小跳）
    children: [
      { path: "/article/category", component: ArticleCategory },
      { path: "/article/ArticleManage", component: ArticleManage },
      { path: "/user/UserAvatar", component: UserAvatar },
      { path: "/user/Userinfo", component: Userinfo },
      { path: "/user/UserResetPassword", component: UserResetPassword },
    ],
    meta: { requiresAuth: true },
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/register",
    name: "Register",
    component: Register,
  },
  {
    path: "/home",
    name: "Home",
    component: Home,
  }
];

//创建路由器
const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;


// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  // 假设你使用localStorage存储了一个token来表示用户登录状态
  const isLoggedIn = localStorage.getItem('token');

  if (to.path.startsWith('/login') && isLoggedIn) {
    // 如果用户尝试访问登录页面，但已经登录，则重定向到主页
    next('/');
  } else if (!isLoggedIn && to.meta.requiresAuth) {
    // 如果用户未登录且尝试访问需要认证的页面，则重定向到登录页面
    next('/login');
  } else {
    // 允许访问
    next();
  }
});
